package com.wondream.myframework.app.common.apollo;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import javafx.util.Pair;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;

import java.util.Collection;
import java.util.Map;

@NoArgsConstructor
public class CfssSpringBootConfigRegistry {

    public static final Map<String, Pair<String, Object>> REGISTRY = Maps.newHashMap();

    private static ConfigurationPropertiesBindingPostProcessor configurationPropertiesBindingPostProcessor;

    public static void register(String key, Pair<String, Object> springValue, ConfigurationPropertiesBindingPostProcessor cpp){
        REGISTRY.put(key, springValue);
        configurationPropertiesBindingPostProcessor = cpp;
    }

    public static Collection<Pair<String, Object>> get(String key){
        Collection<Pair<String, Object>> collection = Lists.newArrayList();
        REGISTRY.keySet().forEach(k -> {
            if (key.indexOf(k) == 0) {
                collection.add(REGISTRY.get(k));
            }
        });
        return collection;
    }

    public static void bind(Pair<String, Object> pair){
        configurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(pair.getKey(), (String)pair.getValue());
    }
}
